﻿using System;
using System.Diagnostics;
using System.IO;

namespace DefenderUI
{
    /// <summary>
    /// A simple static class for logging messages to a file.
    /// It handles thread safety and timestamping of messages.
    /// </summary>
    public static class Logger
    {
        // A thread-safe object to lock on, ensuring that only one thread can write to the log file at a time.
        private static readonly object _logLock = new object();
        // The path for the log file, placed in the same directory as the application executable.
        private static readonly string _logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DefenderUI_Log.txt");

        /// <summary>
        /// Writes a message to the log file with a timestamp.
        /// </summary>
        /// <param name="message">The message to log.</param>
        public static void Log(string message)
        {
            // Lock ensures that if two log events happen simultaneously from different threads,
            // they will write to the file one after the other, preventing corruption.
            lock (_logLock)
            {
                try
                {
                    // Construct the full log entry with a standardized timestamp format.
                    string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] - {message}{Environment.NewLine}";
                    // Append the text to the log file. The file is created if it doesn't exist.
                    File.AppendAllText(_logFilePath, logEntry);
                }
                catch (Exception ex)
                {
                    // If logging itself fails, write the error to the debug console.
                    // This prevents the logger from causing a crash.
                    Debug.WriteLine($"Failed to write to log: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// Gets the full path to the log file.
        /// </summary>
        public static string GetLogFilePath()
        {
            return _logFilePath;
        }
    }
}